<template>
  <div class="chat-container">
    <!-- 会话列表 -->
    <div class="conversation-list">
      <div class="conversation-header">
        <h2>消息</h2>
        <el-button
          type="primary"
          size="small"
          @click="showNewChatDialog = true"
        >
          新建会话
        </el-button>
      </div>

      <div class="conversation-items">
        <div
          v-for="conv in conversations"
          :key="conv.id"
          class="conversation-item"
          :class="{ active: conv.id === activeConversationId }"
          @click="selectConversation(conv.id)"
        >
          <el-avatar :src="conv.avatar || '/default-avatar.png'" :size="48" />
          
          <div class="conversation-info">
            <div class="conversation-name">
              {{ getConversationName(conv) }}
              <el-badge
                v-if="conv.unreadCount > 0"
                :value="conv.unreadCount"
                :max="99"
                class="unread-badge"
              />
            </div>
            
            <div class="last-message">
              {{ formatLastMessage(conv.lastMessage) }}
            </div>
          </div>
          
          <div class="conversation-time">
            {{ formatTime(conv.lastMessage?.createdAt || conv.createdAt) }}
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-area" v-if="activeConversation">
      <!-- AI助手工具栏 -->
      <AIAssistant />
      
      <!-- 聊天头部 -->
      <div class="chat-header">
        <div class="chat-title">
          <h3>{{ getConversationName(activeConversation) }}</h3>
          <span class="participant-count">
            {{ activeConversation.participants.length }}人
          </span>
        </div>
        
        <div class="chat-actions">
          <el-button text @click="showConversationInfo = true">
            详情
          </el-button>
        </div>
      </div>

      <!-- 消息列表 -->
      <div
        class="message-list"
        ref="messageListRef"
        @scroll="handleScroll"
      >
        <div v-if="hasMore.get(activeConversationId)" class="load-more">
          <el-button
            text
            size="small"
            :loading="loading"
            @click="loadMore"
          >
            加载更多消息
          </el-button>
        </div>

        <div
          v-for="message in activeMessages"
          :key="message.id"
          class="message-item"
          :class="{ 'is-self': message.senderId === currentUserId }"
        >
          <el-avatar
            v-if="message.senderId !== currentUserId"
            :src="message.senderAvatar || '/default-avatar.png'"
            :size="40"
          />
          
          <div class="message-content-wrapper">
            <div class="message-sender" v-if="message.senderId !== currentUserId">
              {{ message.senderName || '未知用户' }}
            </div>
            
            <div
              class="message-content"
              :class="`message-type-${message.messageType.toLowerCase()}`"
            >
              <!-- 文本消息 -->
              <template v-if="message.messageType === 'TEXT'">
                <div v-if="message.recalled" class="recalled-message">
                  {{ message.senderId === currentUserId ? '你' : message.senderName }}撤回了一条消息
                </div>
                <div v-else class="text-content">
                  {{ message.content }}
                </div>
              </template>

              <!-- 图片消息 -->
              <template v-else-if="message.messageType === 'IMAGE'">
                <el-image
                  :src="message.content"
                  fit="cover"
                  style="max-width: 300px; max-height: 300px"
                  :preview-src-list="[message.content]"
                />
              </template>

              <!-- 文件消息 -->
              <template v-else-if="message.messageType === 'FILE'">
                <div class="file-message">
                  <i class="el-icon-document"></i>
                  <span>{{ message.content }}</span>
                </div>
              </template>

              <!-- 系统消息 -->
              <template v-else-if="message.messageType === 'SYSTEM'">
                <div class="system-message">
                  {{ message.content }}
                </div>
              </template>
            </div>

            <div class="message-time">
              {{ formatMessageTime(message.createdAt) }}
              
              <el-dropdown
                v-if="message.senderId === currentUserId && !message.recalled"
                trigger="click"
                @command="handleMessageAction"
              >
                <span class="message-actions">
                  <i class="el-icon-more"></i>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{ action: 'recall', messageId: message.id }">
                      撤回
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>

          <el-avatar
            v-if="message.senderId === currentUserId"
            :src="message.senderAvatar || '/default-avatar.png'"
            :size="40"
          />
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <div class="input-toolbar">
          <el-button text size="small">
            <i class="el-icon-picture"></i>
          </el-button>
          <el-button text size="small">
            <i class="el-icon-folder"></i>
          </el-button>
        </div>
        
        <el-input
          v-model="messageInput"
          type="textarea"
          :rows="3"
          placeholder="输入消息..."
          @keydown.enter.exact.prevent="sendMessage"
          @keydown.ctrl.enter="messageInput += '\n'"
        />
        
        <div class="input-actions">
          <span class="input-tip">按Enter发送，Ctrl+Enter换行</span>
          <el-button
            type="primary"
            :loading="sendingMessage"
            :disabled="!messageInput.trim()"
            @click="sendMessage"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-empty description="选择一个会话开始聊天" />
    </div>

    <!-- 新建会话对话框 -->
    <el-dialog
      v-model="showNewChatDialog"
      title="新建会话"
      width="400px"
    >
      <!-- TODO: 实现新建会话逻辑 -->
      <el-form>
        <el-form-item label="会话类型">
          <el-radio-group v-model="newChatType">
            <el-radio label="DIRECT">单聊</el-radio>
            <el-radio label="GROUP">群聊</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useConversationStore } from '@/stores/conversation'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import AIAssistant from '@/components/AIAssistant.vue'

dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const conversationStore = useConversationStore()
const userStore = useUserStore()

const messageInput = ref('')
const messageListRef = ref<HTMLElement>()
const showNewChatDialog = ref(false)
const showConversationInfo = ref(false)
const newChatType = ref<'DIRECT' | 'GROUP'>('DIRECT')

const conversations = computed(() => conversationStore.conversations)
const activeConversationId = computed(() => conversationStore.activeConversationId)
const activeConversation = computed(() => conversationStore.activeConversation)
const activeMessages = computed(() => conversationStore.activeMessages)
const sendingMessage = computed(() => conversationStore.sendingMessage)
const loading = computed(() => conversationStore.loading)
const hasMore = computed(() => conversationStore.messages)
const currentUserId = computed(() => userStore.user?.id || '')

onMounted(async () => {
  await conversationStore.loadConversations()
})

onUnmounted(() => {
  conversationStore.cleanup()
})

const selectConversation = (conversationId: string) => {
  conversationStore.setActiveConversation(conversationId)
  nextTick(() => {
    scrollToBottom()
  })
}

const sendMessage = async () => {
  if (!messageInput.value.trim() || !activeConversationId.value) return
  
  try {
    await conversationStore.sendMessage(
      activeConversationId.value,
      messageInput.value.trim()
    )
    
    messageInput.value = ''
    
    nextTick(() => {
      scrollToBottom()
    })
  } catch (error) {
    // 错误已在store中处理
  }
}

const loadMore = async () => {
  if (!activeConversationId.value) return
  await conversationStore.loadMoreMessages(activeConversationId.value)
}

const handleMessageAction = ({ action, messageId }: { action: string, messageId: string }) => {
  if (action === 'recall') {
    conversationStore.recallMessage(messageId)
  }
}

const handleScroll = (e: Event) => {
  const target = e.target as HTMLElement
  // 检查是否滚动到顶部，加载更多
  if (target.scrollTop === 0 && hasMore.value.get(activeConversationId.value || '')) {
    loadMore()
  }
}

const scrollToBottom = () => {
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight
  }
}

const getConversationName = (conv: any) => {
  if (conv.type === 'DIRECT') {
    const otherUser = conv.participants.find((p: any) => p.userId !== currentUserId.value)
    return otherUser?.username || '未知用户'
  }
  return conv.name || '群聊'
}

const formatLastMessage = (lastMessage: any) => {
  if (!lastMessage) return ''
  
  switch (lastMessage.messageType) {
    case 'TEXT':
      return lastMessage.content
    case 'IMAGE':
      return '[图片]'
    case 'FILE':
      return '[文件]'
    case 'VOICE':
      return '[语音]'
    case 'VIDEO':
      return '[视频]'
    default:
      return ''
  }
}

const formatTime = (time: string) => {
  return dayjs(time).fromNow()
}

const formatMessageTime = (time: string) => {
  const messageTime = dayjs(time)
  const now = dayjs()
  
  if (now.diff(messageTime, 'day') === 0) {
    return messageTime.format('HH:mm')
  } else if (now.diff(messageTime, 'day') === 1) {
    return '昨天 ' + messageTime.format('HH:mm')
  } else {
    return messageTime.format('MM-DD HH:mm')
  }
}
</script>

<style scoped lang="scss">
.chat-container {
  display: flex;
  height: 100vh;
  background: #f5f5f5;
}

.conversation-list {
  width: 300px;
  background: white;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  
  .conversation-header {
    padding: 16px;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h2 {
      margin: 0;
      font-size: 18px;
    }
  }
  
  .conversation-items {
    flex: 1;
    overflow-y: auto;
  }
  
  .conversation-item {
    padding: 12px 16px;
    display: flex;
    gap: 12px;
    cursor: pointer;
    transition: background 0.2s;
    
    &:hover {
      background: #f5f5f5;
    }
    
    &.active {
      background: #e3f2fd;
    }
    
    .conversation-info {
      flex: 1;
      min-width: 0;
      
      .conversation-name {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 500;
        margin-bottom: 4px;
      }
      
      .last-message {
        font-size: 13px;
        color: #999;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    
    .conversation-time {
      font-size: 12px;
      color: #999;
    }
  }
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  
  .chat-header {
    padding: 16px;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .chat-title {
      display: flex;
      align-items: center;
      gap: 12px;
      
      h3 {
        margin: 0;
        font-size: 16px;
      }
      
      .participant-count {
        font-size: 13px;
        color: #999;
      }
    }
  }
  
  .message-list {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    display: flex;
    flex-direction: column-reverse;
    
    .load-more {
      text-align: center;
      padding: 8px;
    }
    
    .message-item {
      display: flex;
      gap: 12px;
      margin-bottom: 16px;
      
      &.is-self {
        flex-direction: row-reverse;
        
        .message-content-wrapper {
          align-items: flex-end;
        }
        
        .message-content {
          background: #1890ff;
          color: white;
        }
      }
      
      .message-content-wrapper {
        display: flex;
        flex-direction: column;
        max-width: 60%;
        
        .message-sender {
          font-size: 12px;
          color: #999;
          margin-bottom: 4px;
        }
        
        .message-content {
          padding: 10px 14px;
          border-radius: 8px;
          background: #f0f0f0;
          word-break: break-word;
          
          .recalled-message {
            color: #999;
            font-style: italic;
          }
          
          .system-message {
            background: transparent;
            color: #999;
            text-align: center;
            font-size: 12px;
          }
        }
        
        .message-time {
          font-size: 12px;
          color: #999;
          margin-top: 4px;
          display: flex;
          align-items: center;
          gap: 8px;
        }
      }
    }
  }
  
  .chat-input {
    border-top: 1px solid #e0e0e0;
    padding: 16px;
    
    .input-toolbar {
      margin-bottom: 8px;
    }
    
    .input-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 8px;
      
      .input-tip {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
}
</style>
